package com.dd.shop4j.console.order.service;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dd.shop4j.common.utils.Page;
import com.dd.shop4j.console.order.controller.forms.OrderQueryForm;
import com.dd.shop4j.goods.mapper.GoodsInfoMapper;
import com.dd.shop4j.goods.model.GoodsInfo;
import com.dd.shop4j.order.mapper.OrderDetailsMapper;
import com.dd.shop4j.order.mapper.OrderInfoMapper;
import com.dd.shop4j.order.model.OrderDetails;
import com.dd.shop4j.order.model.OrderInfo;

/**
 * 订单管理业务类 <br />
 * <ul style="list-style: decimal;">
 * <li>分页条件查询订单信息</li>
 * </ul>
 * 
 * @author tangshu
 * 
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderManagerService {

	private static final Logger logger = Logger.getLogger(OrderManagerService.class);
	
	@Resource private OrderInfoMapper orderInfoMapper;
	@Resource private OrderDetailsMapper orderDetailsMapper;
	@Resource private GoodsInfoMapper goodsInfoMapper;
	
	/**
	 * 分页条件查询订单信息
	 * @param orderInfo	订单的查询条件
	 * @param curpage	当前页码
	 * @param pagesize	页大小
	 * @return
	 */
	public Page<OrderInfo> queryOrderInfoByPage(OrderQueryForm orderInfo,
			int curpage, int pagesize) {
		//分也条件查询出订单数据集
		List<OrderInfo> orders = orderInfoMapper.queryOrdersByPage(orderInfo, (curpage - 1) * pagesize, pagesize, "add_time", "desc");
		for (OrderInfo order : orders) {
			fillDetails(order);
		}
		logger.debug("订单查询结果:" + JSONArray.fromObject(orders));
		//查询出订单的总数量
		int count = orderInfoMapper.queryOrdersCount(orderInfo);
		return new Page<OrderInfo>(orders, count, curpage, pagesize);
	}
	
	/**
	 * 填充订单信息
	 * @param order 订单对象
	 */
	private void fillDetails(OrderInfo order) {
		OrderDetails detail = new OrderDetails();
		detail.setOrderId(order.getId());
		List<OrderDetails> ds = orderDetailsMapper.queryBySelective(detail);
		List<GoodsInfo> goods = goodsInfoMapper.getGoodsByOrderId(order.getId());
		for (OrderDetails d : ds) {
			for (GoodsInfo good : goods) {
				if (d.getGoodId().equals(good.getId())) {
					d.setGood(good);
					break;
				}
			}
			order.addDetail(d);
		}
	}
	
}
